<template>
  <van-button
    class="follow-btn"
    type="info"
    color="#3296fa"
    round
    v-if="!value"
    size="small"
    icon="plus"
    :loading="loading"
    @click="onFollow"
  >关注</van-button>
  <van-button
    v-else
    class="follow-btn"
    round
    :loading="loading"
    size="small"
    @click="onFollow"
  >已关注</van-button>
</template>

<script>
import { addFollow, deleteFollow } from '@/api/user'
export default {
  name: 'follow-user',
  data () {
    return {
      loading: false
    }
  },

  props: {
    value: {
      type: Boolean,
      required: true
    },
    user_id: {
      type: [Number, String, Object],
      required: true
    }
  },

  created () {

  },

  methods: {
    // 关注用户
    async onFollow () {
      this.loading = true
      try {
        // 如果已关注，则取消关注
        if (this.value) {
          await deleteFollow(this.user_id)
        } else {
          // 否则添加关注
          await addFollow(this.user_id)
        }

        // 更新视图
        this.$emit('input', !this.value)
      } catch (err) {
        // console.dir(err)
        if (err.response && err.response.status === 400) {
          return this.$toast.fail('不能关注自己！')
        }
        this.$toast.fail('操作失败，请重试！')
      }

      // 关闭按钮的 loading 状态
      this.loading = false
    }
  }
}
</script>

<style scoped lang='less'>

</style>
